// 监听扩展安装或更新事件
chrome.runtime.onInstalled.addListener(() => {
  console.log('Google Analytics Tester 扩展已安装');
});

// 监听扩展图标点击事件
chrome.action.onClicked.addListener((tab) => {
  console.log('扩展图标被点击');
});

const GA_TRACKING_ID = 'G-BYE88EHR7Z';
const GA_ENDPOINT = 'https://www.google-analytics.com/g/collect';

// 生成随机的客户端ID
function generateClientId() {
  return Math.floor(Math.random() * 1000000000) + '.' + Date.now();
}

// 监听来自 content script 的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'GA_EVENT') {
    const clientId = generateClientId();
    const sessionId = Date.now();
    // 构建事件数据
    const eventData = message.data;

    // 构建基础查询参数
    const baseParams = new URLSearchParams({
      v: '2',
      tid: GA_TRACKING_ID,
      cid: clientId,
      sid: sessionId,
      dl: sender.tab?.url || eventData.params.page_path,
      dt: sender.tab?.title || eventData.params.page_title
      ,
      ul: navigator.language || 'zh-cn',
    });

    const body = `en=${eventData.type}&_ee=1` +
                 (eventData.params ? Object.entries(eventData.params)
                   .map(([key, value]) => `&ep.${key}=${value}`)
                   .join('') : '') +
                 `&_et=${Math.floor(Math.random() * 10000)}`;
    // console.log("baseParams", baseParams);
    // 发送请求
    fetch(`${GA_ENDPOINT}?${baseParams.toString()}`, {
      method: 'POST',
      body: body,
      headers: {
        'Content-Type': 'text/plain;charset=UTF-8',
      },
    }).then(() => {
      console.log('GA 事件已发送:', eventData);
      sendResponse({ status: 'success' });
    }).catch(error => {
      console.error('GA 事件发送失败:', error);
      sendResponse({ status: 'error', error });
    });
  }
  return true;
}); 